package com.wanqh.reptitle.service.xinlangweibo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.wanqh.reptitle.service.SearchService;
import com.wanqh.reptitle.utils.ExcelUtil;
import com.wanqh.reptitle.utils.SpiderUtils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service("weiBoSearchService")
@Slf4j
public class WeiBoSearchServiceImpl implements SearchService {

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    @Autowired
    @Qualifier("firefoxWebDriver")
    private WebDriver firefoxWebDriver;

    @Override
    public String getPlatform() {
        return "新浪微博";
    }

    @Override
    public void initExcel() throws Exception {
        ExcelUtil.initExcel(getPlatform(), new String[]{"文件品牌", "搜索匹配结果", "链接", "微博认证说明", "友情链接"}, SpiderUtils.FILE_PATH);
    }

    @Override
    public String[][] ServiceBrand(@NonNull String brand) {
        if (StrUtil.isEmpty(brand)) {
            return null;
        }
        String url = "https://s.weibo.com/user?q=" + brand + "&auth=org_vip&Refer=SUer_box";

        String[][] result = new String[][]{{brand}};

        Document document = null;
        try {
            document = getWeiboBySelenium(url);
        } catch (Exception e) {
            result[0][1] = "异常";
        }
        if (document != null) {
            Elements userCards = document.getElementsByClass("card card-user-b s-pg16 s-brt1");
            String orgHandle = firefoxWebDriver.getWindowHandle();
            if (CollUtil.isNotEmpty(userCards)) {
                Element userCard = userCards.get(0);
                Element infoEle = userCard.getElementsByClass("info").get(0);
                Element nameEle = infoEle.getElementsByClass("name").get(0);
                String orgHref = "https:" + nameEle.attr("href");
                String text = nameEle.text();

                Element p = infoEle.getElementsByTag("p").get(1);
                String desc = p.text();
                StringBuffer yqUrl = new StringBuffer();
                try {
                    Elements avator = document.getElementsByClass("avator");
                    if (CollUtil.isNotEmpty(avator)) {
                        String href = avator.get(0).getElementsByTag("a").attr("href");
                        if (StringUtils.isNotBlank(href)) {
                            firefoxWebDriver.get("https:" + href);
                            ThreadUtil.sleep(5, TimeUnit.SECONDS);
                            Document parse = Jsoup.parse(firefoxWebDriver.getPageSource());
                            Elements item_s_line2_clearfix = parse.getElementsByClass("item S_line2 clearfix");
                            if (CollUtil.isNotEmpty(item_s_line2_clearfix) && item_s_line2_clearfix.size() >= 4) {
                                Element yqItem = item_s_line2_clearfix.get(3);
                                List<Element> a = yqItem.getElementsByTag("a");
                                if (CollUtil.isNotEmpty(a)) {
                                    for (Element yqEle : a) {
                                        yqUrl.append(yqEle.attr("href"));
                                        yqUrl.append("     ");
                                        yqUrl.append(yqEle.text());
                                        yqUrl.append("\n");
                                    }

                                }
                            }
                            Elements verify_area_w_tog_hover_s_line2 = parse.getElementsByClass("verify_area W_tog_hover S_line2");
                            if (CollUtil.isNotEmpty(verify_area_w_tog_hover_s_line2)) {
                                desc = verify_area_w_tog_hover_s_line2.get(0).getElementsByClass("info").get(0).getElementsByTag("span").get(0).text();
                            }
                        }
                    }
//                    List<WebElement> avator = firefoxWebDriver.findElements(By.className("avator"));

//                    avator.get(0);
//                    ThreadUtil.sleep(5, TimeUnit.SECONDS);

//                    Set<String> windowHandles = firefoxWebDriver.getWindowHandles();
//                    for (String str : windowHandles) {
//                        if (str.equals(orgHandle)) {
//                            continue;
//                        } else {
//                            firefoxWebDriver.switchTo().window(str);
//                            break;
//                        }
//                    }
//                    ThreadUtil.sleep(RandomUtil.randomInt(4, 10), TimeUnit.SECONDS);

//                    firefoxWebDriver.findElements(By.className("WB_cardmore S_txt1 S_line1 clearfix")).get(0).click();
                } catch (Exception e) {
                    log.error(e.getLocalizedMessage());
                } finally {
//                    if (!firefoxWebDriver.getWindowHandle().equals(orgHandle)) {
//                        firefoxWebDriver.close();
//                        firefoxWebDriver.switchTo().window(orgHandle);
//                    }
                }

                if (SpiderUtils.isContains(text, brand)) {
                    result[0] = new String[]{brand, text, orgHref, desc, yqUrl.toString()};
                }
//                log.info("微博:[{}],地址:[{}]",text, orgHref);
            }
        }
        return result;
    }

    private Document getWeiboBySelenium(String url) {
        firefoxWebDriver.get(url);
        // 等待页面加载完成
        ThreadUtil.sleep(RandomUtil.randomInt(1, 5), TimeUnit.SECONDS);
        Document parse = Jsoup.parse(firefoxWebDriver.getPageSource());
        return parse;
    }

    private Document getWeiboByHttp(String url) {
        Document document = null;
        try {
            document = Jsoup.connect(url).timeout(5000)
                    .get();
        } catch (IOException e) {
            try {
                String forObject = restTemplate.getForObject(url, String.class);
                if (StrUtil.isNotEmpty(forObject)) {
                    document = Jsoup.parse(forObject);
                }
            } catch (Exception e1) {
                throw new RuntimeException("微博异常");
            }
        }
        return document;
    }
}
